package com.example.sunming.thread;

/**
 * @description: TestThread
 * @date: 2020/11/12 14:21
 * @author: sunming
 */
public class TestThread {
    static Integer a, b, x, y;
    public static void main(String[] args) throws InterruptedException {
        volatileTest();
    }

    /**
     * 测试指令重排
     */
    public static void volatileTest() throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            a = 0;
            b = 0;
            x = 0;
            y = 0;
            Thread one = new Thread(() -> {
                a = 1;
                b = x;
            });
            Thread other = new Thread(() -> {
                x = 1;
                y = a;
            });
            one.start();
            other.start();
            one.join();
            other.join();
            if (y == 0 && b == 0) {
                System.out.println("在第" + i + "次循环出现指令重排");
                break;
            }
        }
    }
}

